Write a program to check if a given binary tree is a binary search tree.
Write a program to check if a given binary tree is a binary search tree.
504
21-Apr-2023
Updated on 22-Apr-2023
Aryan Kumar
22-Apr-2023In this program, we define the binary tree node structure and a function to create a new binary tree node. We then define a recursive function isBSTUtil that takes a node, a minimum value, and a maximum value as arguments, and returns true if the tree rooted at the node is a binary search tree within the given range. We call this function initially with the root of the binary tree and the minimum and maximum possible integer values. The function returns true if the node is NULL (an empty tree) or if the node's value is within the given range and the left and right subtrees are also binary search trees within their respective ranges. We use INT_MIN and INT_MAX to represent the minimum and maximum integer values respectively.
Finally, we define another function isBST that calls isBSTUtil with the root of the binary tree and returns the result.
In the main function, we create a binary tree and call the isBST function to check if it is a binary search tree. We print the result accordingly.